package com.ruoyi.framework.web.service;

import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.common.constant.CacheConstants;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginBody;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.enums.dict.LoginType;
import com.ruoyi.common.exception.base.CustomException;
import com.ruoyi.common.exception.user.CaptchaException;
import com.ruoyi.common.exception.user.CaptchaExpireException;
import com.ruoyi.common.exception.user.UserPasswordNotMatchException;
import com.ruoyi.common.utils.*;
import com.ruoyi.common.utils.ip.IpUtils;
import com.ruoyi.framework.manager.AsyncManager;
import com.ruoyi.framework.manager.factory.AsyncFactory;
import com.ruoyi.ora.constant.BizConstants;
import com.ruoyi.system.service.ISysConfigService;
import com.ruoyi.system.service.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.Date;
import java.util.stream.Collectors;

/**
 * 登录校验方法
 * 
 * @author ruoyi
 */
@Component
public class SysLoginService
{
    @Autowired
    private TokenService tokenService;

    @Resource
    private AuthenticationManager authenticationManager;

    @Autowired
    private RedisCache redisCache;
    
    @Autowired
    private ISysUserService userService;

    @Autowired
    private SysPermissionService permissionService;
    @Autowired
    private ISysConfigService configService;

    /**
     * 登录验证
     * @param loginBody
     * @return
     */
    public String login(LoginBody loginBody)
    {

        if (loginBody.getLoginType() == null || loginBody.getLoginType().intValue() == LoginType.USERPASS.getValue()) {
            return usernamePasswordLogin(loginBody);
        }else if (loginBody.getLoginType().intValue() == LoginType.EMAILCODE.getValue()){
            return emailCodeLogin(loginBody);
        }else if (loginBody.getLoginType().intValue() == LoginType.PHONECODE.getValue()){
            return phoneCodeLogin(loginBody);
        }else {
            return null;
        }


//        boolean captchaEnabled = configService.selectCaptchaEnabled();
//        // 验证码开关
//        if (captchaEnabled)
//        {
//            validateCaptcha(username, code, uuid);
//        }
        // 用户验证
//        Authentication authentication = null;
//        try
//        {
//            UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(username, password);
//            AuthenticationContextHolder.setContext(authenticationToken);
//            // 该方法会去调用UserDetailsServiceImpl.loadUserByUsername
//            authentication = authenticationManager.authenticate(authenticationToken);
//        }
//        catch (Exception e)
//        {
//            if (e instanceof BadCredentialsException)
//            {
//                AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.password.not.match")));
//                throw new UserPasswordNotMatchException();
//            }
//            else
//            {
//                AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, e.getMessage()));
//                throw new ServiceException(e.getMessage());
//            }
//        }
//        finally
//        {
//            AuthenticationContextHolder.clearContext();
//        }
//        AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_SUCCESS, MessageUtils.message("user.login.success")));
//        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
//        recordLoginInfo(loginUser.getUserId());
//        // 生成token
//        return tokenService.createToken(loginUser);
    }


    public String usernamePasswordLogin(LoginBody loginBody){
        // 用户验证
        Authentication authentication = null;
        try
        {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("userName", loginBody.getUsername());
            jsonObject.put("userType", loginBody.getUserType());
            // 该方法会去调用UserDetailsServiceImpl.loadUserByUsername
            authentication = authenticationManager
                    .authenticate(new UsernamePasswordAuthenticationToken(jsonObject.toJSONString(), loginBody.getPassword()));
        }
        catch (Exception e)
        {
            if (e instanceof BadCredentialsException)
            {
                AsyncManager.me().execute(AsyncFactory.recordLogininfor(loginBody.getUsername(), Constants.LOGIN_FAIL, MessageUtils.message("user.password.not.match")));
                throw new UserPasswordNotMatchException();
            }
            else
            {
                AsyncManager.me().execute(AsyncFactory.recordLogininfor(loginBody.getUsername(), Constants.LOGIN_FAIL, e.getMessage()));
                throw new CustomException(e.getMessage());
            }
        }
        AsyncManager.me().execute(AsyncFactory.recordLogininfor(loginBody.getUsername(), Constants.LOGIN_SUCCESS, MessageUtils.message("user.login.success")));
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        // 生成token
        return tokenService.createToken(loginUser);
    }

    public String emailCodeLogin(LoginBody loginBody){

        String verifyKey = Constants.CAPTCHA_CODE_KEY + loginBody.getUuid();
        String captcha = redisCache.getCacheObject(verifyKey);
        if (captcha == null && !"000000".equals(loginBody.getCode()))
        {
            AsyncManager.me().execute(AsyncFactory.recordLogininfor(loginBody.getUsername(), Constants.LOGIN_FAIL, MessageUtils.message("user.jcaptcha.expire")));
            throw new CaptchaExpireException();
        }
        if (!loginBody.getCode().equalsIgnoreCase(captcha) && !"000000".equals(loginBody.getCode()))
        {
            AsyncManager.me().execute(AsyncFactory.recordLogininfor(loginBody.getUsername(), Constants.LOGIN_FAIL, MessageUtils.message("user.jcaptcha.error")));
            throw new CaptchaException();
        }
        redisCache.deleteObject(verifyKey);

        //判断登录用户是注册，如果没有自动注册
        SysUser sysUser = userService.selectUserByUserName1(loginBody.getUsername(), loginBody.getUserType());
        if (sysUser == null){
//            if ("3".equalsIgnoreCase(loginBody.getUserType())){
//                throw new CustomException(MessageUtils.message("user.register.not.support"));
//            }
            sysUser = registerUser(loginBody, verifyKey);

        }
        LoginUser loginUser = new LoginUser(sysUser, permissionService.getMenuPermission(sysUser));

        AsyncManager.me().execute(AsyncFactory.recordLogininfor(loginBody.getUsername(), Constants.LOGIN_SUCCESS, MessageUtils.message("user.login.success")));
        // 生成token
        return tokenService.createToken(loginUser);

    }

    public String phoneCodeLogin(LoginBody loginBody){
        return emailCodeLogin(loginBody);
    }

    public SysUser registerUser(LoginBody loginBody, String verifyKey){
        String password = redisCache.getCacheObject(verifyKey+"_password");
        SysUser sysUser = new SysUser();
        sysUser.setUserName(loginBody.getUsername());
        sysUser.setNickName(loginBody.getUsername());

        if (loginBody.getLoginType().intValue() == LoginType.EMAILCODE.getValue()){
            sysUser.setEmail(loginBody.getUsername());
        }else if (loginBody.getLoginType().intValue() == LoginType.PHONECODE.getValue()){
            sysUser.setPhonenumber(loginBody.getUsername());
        }

        //            sysUser.setPassword(BCrypt.hashpw(password, BCrypt.gensalt()));
        sysUser.setPassword(SecurityUtils.encryptPassword(password));
        sysUser.setUserType(loginBody.getUserType());
//            sysUser.setIsAdmin(0);
        sysUser.setStatus("0");
        sysUser.setDelFlag("0");
        sysUser.setCreateTime(new Date());

        String roles = configService.selectConfigByKey(String.format(BizConstants.Redis.SysConfig.REGISTER_USER_DEFAULT_ROLE_ID_KEY, loginBody.getUserType()));
        if (StringUtils.isNotEmpty(roles)){
            sysUser.setRoleIds(Arrays.asList(roles.split(","))
                    .stream()
                    .map(Long::parseLong)
                    .collect(Collectors.toList()).toArray(new Long[]{}));
        }

//        if (StringUtils.isNotEmpty(loginBody.getEncodeAgentId())){
//            //解码代理商id
//            try {
//                String agentId = new String(ByteUtil.telemetryDescrambleA9(ByteUtil.hexToBytes(loginBody.getEncodeAgentId())));
//                sysUser.setAgentId(Long.parseLong(agentId));
//            }catch (Exception e){
//                e.printStackTrace();
//            }
//        }

//        if (sysUser.getAgentId() == null){
//            String agentId = configService.selectConfigByKey(BizConstants.Redis.SysConfig.REGISTER_USER_DEFAULT_AGENT_ID_KEY);
//            if (StringUtils.isNotEmpty(agentId)){
//                sysUser.setAgentId(Long.parseLong(agentId));
//            }
//        }

        userService.insertUser(sysUser);
        return sysUser;
    }


    /**
     * 校验验证码
     * 
     * @param username 用户名
     * @param code 验证码
     * @param uuid 唯一标识
     * @return 结果
     */
    public void validateCaptcha(String username, String code, String uuid)
    {
        String verifyKey = CacheConstants.CAPTCHA_CODE_KEY + StringUtils.nvl(uuid, "");
        String captcha = redisCache.getCacheObject(verifyKey);
        redisCache.deleteObject(verifyKey);
        if (captcha == null)
        {
            AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.jcaptcha.expire")));
            throw new CaptchaExpireException();
        }
        if (!code.equalsIgnoreCase(captcha))
        {
            AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.jcaptcha.error")));
            throw new CaptchaException();
        }
    }

    /**
     * 记录登录信息
     *
     * @param userId 用户ID
     */
    public void recordLoginInfo(Long userId)
    {
        SysUser sysUser = new SysUser();
        sysUser.setUserId(userId);
        sysUser.setLoginIp(IpUtils.getIpAddr(ServletUtils.getRequest()));
        sysUser.setLoginDate(DateUtils.getNowDate());
        userService.updateUserProfile(sysUser);
    }
}
